package com.itboye.mengwu.app.ui.mymeng.personsettings;

import java.text.SimpleDateFormat;
import java.util.Observable;
import java.util.Observer;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.DebugLog;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.chatemoji.FaceInputView;
import com.itboye.mengwu.chatemoji.FaceInputView.Face;
import com.itboye.mengwu.chatemoji.FaceInputView.OnFaceClickListener;
import com.itboye.mengwu.data.model.SiXinXiangQingModel;
import com.itboye.mengwu.data.presenter.PrivatePresenter;
import com.itboye.sunsun.volley.Spanned2String;

public class ActivitySiXinXiangQing extends BaseActivity implements Observer,
		SwipeRefreshLayout.OnRefreshListener {

	ListView lv;
	MessageTotalAdapter messageTotalAdapter;
	// ArrayList<TextBean> textBeans;

	String currUid, relaUid, toNick;
	ImageView back;
	TextView txt_title, btn_send;

	PrivatePresenter privatePresenter;
	SiXinXiangQingModel siXinXiangQingModel, siXinXiangQingModel1;
	EditText edt_comments;

	String message;

	private FaceInputView faceInputView;
	private LinearLayout faceInputContainer;
	ImageView emoji;
	Boolean isShowEmotion = false;

	// 下拉刷新
	private SwipeRefreshLayout mSwipeLayout;
	private static final int REFRESH_COMPLETE = 0X110;

	int page = 1;
	String xialajiazai = "0";

	// 倒叙显示
	int size, totalPage;
	LinearLayout huifu;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case REFRESH_COMPLETE:
				// mDatas.addAll(Arrays.asList("Lucene", "Canvas", "Bitmap"));
				page--;
				xialajiazai = "1";
				privatePresenter.SiXinXiangQing(currUid, relaUid, "",
						page + "", "18");

				messageTotalAdapter.notifyDataSetChanged();
				mSwipeLayout.setRefreshing(false);
				break;

			}
		};
	};
	protected String con;

	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);

		if (entity != null) {
			if (entity.getEventType() == privatePresenter.sixinxiangqing_success) {

				if (page <= 0) {
					return;
				}
				Log.e("page", page + "");

				if ("1".equals(xialajiazai)) {
					Log.e("222", "asdf");
					siXinXiangQingModel = (SiXinXiangQingModel) entity
							.getData();
					siXinXiangQingModel.getList().addAll(
							siXinXiangQingModel1.getList());
					messageTotalAdapter = new MessageTotalAdapter(
							siXinXiangQingModel, this);
					siXinXiangQingModel1 = siXinXiangQingModel;
					lv.setAdapter(messageTotalAdapter);
					lv.setSelection(18);

				} else if ("0".equals(xialajiazai)) {
					Log.e("111", "asdf");
					siXinXiangQingModel1 = new SiXinXiangQingModel();
					siXinXiangQingModel = (SiXinXiangQingModel) entity
							.getData();
					siXinXiangQingModel1 = siXinXiangQingModel;
					messageTotalAdapter = new MessageTotalAdapter(
							siXinXiangQingModel, this);
					lv.setAdapter(messageTotalAdapter);
					lv.setSelection(lv.getBottom());

					size = siXinXiangQingModel.getCount();

					if (size % 18 == 0) {
						totalPage = size / 18;
					} else {
						totalPage = size / 18 + 1;
					}

					page = totalPage;
					Log.e("totalPage", totalPage + "");
				}
				// siXinXiangQingModel = (SiXinXiangQingModel) entity.getData();
				// messageTotalAdapter = new
				// MessageTotalAdapter(siXinXiangQingModel, this);

			} else if (entity.getEventType() == privatePresenter.sixinxiangqing_fail) {

			}
			if (entity.getEventType() == privatePresenter.sixinfasong_success) {
				String info = (String) entity.getData();
				if ("发送成功".equals(info)) {
					ByAlert.alert(info);
					edt_comments.setText("");
				} else {
					ByAlert.alert(info);
				}
				page = totalPage;
				xialajiazai = "0";
				privatePresenter = new PrivatePresenter(this);
				privatePresenter
						.SiXinXiangQing(currUid, relaUid, "", "0", "18");

			} else if (entity.getEventType() == privatePresenter.sixinfasong_fail) {

			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	public int initView() {
		return R.layout.activity_sixin_xiangqing;
	}

	@Override
	public void onMyCreate() {

		Intent intent = getIntent();
		currUid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
		relaUid = intent.getStringExtra("rela_uid");
		toNick = intent.getStringExtra("to_nick");
		mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
		mSwipeLayout.setOnRefreshListener(this);
		mSwipeLayout.setColorScheme(android.R.color.holo_green_dark,
				android.R.color.holo_green_light,
				android.R.color.holo_orange_light,
				android.R.color.holo_red_light);
		IntentFilter filter = new IntentFilter("privatemsg");
		registerReceiver(receiver, filter);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
		if (toNick == null || "".equals(relaUid)) {
			huifu.setVisibility(View.GONE);
		}
		txt_title.setText(toNick);
		privatePresenter = new PrivatePresenter(this);
		privatePresenter.SiXinXiangQing(currUid, relaUid, "", "0", "18");

		btn_send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				message = edt_comments.getText().toString().trim();
				if (TextUtils.isEmpty(message)) {
					ByAlert.alert("不能发送空消息！");
				} else {
					showProgressDialog("消息发送中...", true);
					con = Spanned2String.parse(edt_comments.getText());
					System.out.println("消息来了热" + con);
					privatePresenter.FaSongSiXin(currUid, relaUid,
							Spanned2String.parse(edt_comments.getText()));
					edt_comments.setText("");
				}

			}
		});
		// 表情
		faceInputView = new FaceInputView(this, 1);
		faceInputContainer.addView(faceInputView);
		faceInputView.setOnClickListener(new FaceInputListenr());

		emoji.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!isShowEmotion) {
					faceInputContainer.setVisibility(View.VISIBLE);
					lv.setSelection(lv.getBottom());
					lv.smoothScrollToPosition(lv.getBottom());
				} else {
					faceInputContainer.setVisibility(View.GONE);
					lv.setSelection(lv.getBottom());
					lv.smoothScrollToPosition(lv.getBottom());
				}
				isShowEmotion = !isShowEmotion;
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(ActivitySiXinXiangQing.this
								.getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);

			}
		});
		edt_comments.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!isShowEmotion) {
					faceInputContainer.setVisibility(View.VISIBLE);
					lv.setSelection(lv.getBottom());
					lv.smoothScrollToPosition(lv.getBottom());
				} else {
					faceInputContainer.setVisibility(View.GONE);
					lv.setSelection(lv.getBottom());
					lv.smoothScrollToPosition(lv.getBottom());
				}
				isShowEmotion = !isShowEmotion;

				// if (getWindow().getAttributes().softInputMode ==
				// WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED
				// && faceInputContainer.getVisibility()==View.VISIBLE){
				// // 隐藏软键盘
				// getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
				// getWindow().getAttributes().softInputMode =
				// WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED;
				// // faceInputContainer.setVisibility(View.GONE);
				//
				//
				// }

			}
		});

		lv.setSelection(lv.getBottom());
		lv.smoothScrollToPosition(lv.getBottom());
		showProgressDialog("消息加载中...", true);

	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			DebugLog.v("bytag", ">>>>>>>");
			privatePresenter.SiXinXiangQing(currUid, relaUid, "", "0", "18");
		}
	};

	public class MessageTotalAdapter extends BaseAdapter {

		SiXinXiangQingModel siXinXiangQingModel;
		Context context;
		SimpleDateFormat myFmt1 = new SimpleDateFormat("yyyy-MM-dd");// 年月日的格式
		SimpleDateFormat myFmt2 = new SimpleDateFormat("HH:mm:ss");// 时分秒的格式
		SimpleDateFormat myFmt3 = new SimpleDateFormat("m分钟前");// 最后做时间差用的分钟
		SimpleDateFormat myFmt4 = new SimpleDateFormat("H小时前");// 最后做时间差用的小时
		String result;

		class Holder1 {
			TextView timeTv, messageTv;

			Holder1(View view) {
				timeTv = (TextView) view.findViewById(R.id.timeTv);
				messageTv = (TextView) view.findViewById(R.id.messageTv);
			}

		}

		class Holder2 {
			TextView timeTv, messageTv;

			Holder2(View view) {
				timeTv = (TextView) view.findViewById(R.id.timeTv);
				messageTv = (TextView) view.findViewById(R.id.messageTv);
			}
		}

		public MessageTotalAdapter(SiXinXiangQingModel siXinXiangQingModel,
				Context context) {
			super();
			this.siXinXiangQingModel = siXinXiangQingModel;
			this.context = context;
			notifyDataSetChanged();
		}

		@Override
		public int getItemViewType(int position) {

			if (currUid.equals(siXinXiangQingModel.getList().get(position)
					.getFromId())) {
				return 2;
			} else if (currUid.equals(siXinXiangQingModel.getList()
					.get(position).getToId())) {
				return 1;
			}
			return 0;
		}

		@Override
		public int getViewTypeCount() {
			// TODO Auto-generated method stub
			return 3;
		}

		@Override
		public int getCount() {
			return siXinXiangQingModel.getList() != null ? siXinXiangQingModel
					.getList().size() : 0;
		}

		@Override
		public Object getItem(int position) {
			return siXinXiangQingModel.getList().get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int type = getItemViewType(position);

			Holder1 holder1 = null;
			Holder2 holder2 = null;

			if (convertView == null) {
				// 选择某一个样式。。
				switch (type) {
				case 1:
					convertView = LayoutInflater.from(context).inflate(
							R.layout.item_sixin_receive, null);
					holder1 = new Holder1(convertView);

					convertView.setTag(holder1);
					break;
				case 2:
					convertView = LayoutInflater.from(context).inflate(
							R.layout.item_sixin_send, null);
					holder2 = new Holder2(convertView);

					convertView.setTag(holder2);
					break;
				default:
					break;
				}
			} else {
				switch (type) {
				case 1:
					holder1 = (Holder1) convertView.getTag();

					break;
				case 2:
					holder2 = (Holder2) convertView.getTag();

					break;

				default:
					break;
				}

			}

			// 获取当前年月日
			String nowDay = myFmt1.format(System.currentTimeMillis());
			// 获取该position下的帖子年月日
			String positionDay = myFmt1.format(Long
					.parseLong(siXinXiangQingModel.getList().get(position)
							.getSendTime()
							+ "") * 1000);
			// 获取该position下的帖子时分秒
			String positionTime = myFmt2.format(Long
					.parseLong(siXinXiangQingModel.getList().get(position)
							.getSendTime()
							+ "") * 1000);

			switch (type) {
			case 1:

				// 如果是当天显示时和分， 如果超过一天显示日期
				if (nowDay.equals(positionDay)) {

					Log.e("--------",
							System.currentTimeMillis()
									- Long.parseLong(siXinXiangQingModel
											.getList().get(position)
											.getSendTime()
											+ "") * 1000 + "");
					// 3600000是一个小时的时间戳
					// 如果大于一个小时只显示小时，如果小与一个小时显示分钟
					if (3600000 > System.currentTimeMillis()
							- Long.parseLong(siXinXiangQingModel.getList()
									.get(position).getSendTime()
									+ "") * 1000) {

						result = myFmt3.format(System.currentTimeMillis()
								- Long.parseLong(siXinXiangQingModel.getList()
										.get(position).getSendTime()
										+ "") * 1000);
						Log.e("--------", "小于一个小时" + result);
						// 如果小于1分钟
						if (60000 > System.currentTimeMillis()
								- (Long.parseLong(siXinXiangQingModel.getList()
										.get(position).getSendTime())) * 1000) {
							result = "刚刚";
						}

					} else {
						result = myFmt4.format(System.currentTimeMillis()
								- Long.parseLong(siXinXiangQingModel.getList()
										.get(position).getSendTime()
										+ "") * 1000);
						Log.e("--------", "大于一个小时" + result);
					}
					holder1.timeTv.setText(result);
				} else {
					holder1.timeTv.setText(positionDay);

				}
				holder1.messageTv.setText(siXinXiangQingModel.getList()
						.get(position).getContent());
				break;
			case 2:

				// 如果是当天显示时和分， 如果超过一天显示日期
				if (nowDay.equals(positionDay)) {

					Log.e("--------",
							System.currentTimeMillis()
									- Long.parseLong(siXinXiangQingModel
											.getList().get(position)
											.getSendTime()
											+ "") * 1000 + "");
					// 3600000是一个小时的时间戳
					// 如果大于一个小时只显示小时，如果小与一个小时显示分钟
					if (3600000 > System.currentTimeMillis()
							- Long.parseLong(siXinXiangQingModel.getList()
									.get(position).getSendTime()
									+ "") * 1000) {
						result = myFmt3.format(System.currentTimeMillis()
								- Long.parseLong(siXinXiangQingModel.getList()
										.get(position).getSendTime()
										+ "") * 1000);
						Log.e("--------", "小于一个小时" + result);
						// 如果小于1分钟
						Log.e("!!!1", System.currentTimeMillis() + "");
						Log.e("!!!2",
								Integer.parseInt(siXinXiangQingModel.getList()
										.get(position).getSendTime())
										+ "");
						Log.e("!!!3",
								System.currentTimeMillis()
										- (Long.parseLong(siXinXiangQingModel
												.getList().get(position)
												.getSendTime())) * 1000 + "");
						if (60000 > System.currentTimeMillis()
								- (Long.parseLong(siXinXiangQingModel.getList()
										.get(position).getSendTime())) * 1000) {
							result = "刚刚";
						}
					} else {
						result = myFmt4.format(System.currentTimeMillis()
								- Long.parseLong(siXinXiangQingModel.getList()
										.get(position).getSendTime()
										+ "") * 1000);
						Log.e("--------", "大于一个小时" + result);
					}
					holder2.timeTv.setText(result);
				} else {
					holder2.timeTv.setText(positionDay);

				}
				holder2.messageTv.setText(siXinXiangQingModel.getList()
						.get(position).getContent());
				break;

			}

			return convertView;
		}

	}

	// 输入表情需要
	ImageGetter imageGetter = new ImageGetter() {
		@Override
		public Drawable getDrawable(String source) {
			int id = Integer.parseInt(source);
			@SuppressWarnings("deprecation")
			Drawable d = getResources().getDrawable(id);
			d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
			return d;
		}
	};

	class FaceInputListenr implements OnFaceClickListener {

		@Override
		public void selectedFace(Face face) {
			int id = face.faceId;
			if (id == R.drawable.ic_face_delete_normal)// 删除按钮
			{
				int index = edt_comments.getSelectionStart();
				if (index == 0)
					return;
				Editable editable = edt_comments.getText();
				editable.delete(index - 1, index);// 删除最后一个字符或表情
			} else {
				edt_comments.append(Html.fromHtml("<img src='" + id + "'/>",
						imageGetter, null));// 添加表情
			}
		}

	}

	@Override
	public void onRefresh() {

		mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 2000);

	}

}
